import re
import json
import requests
from bs4 import BeautifulSoup
import datetime
import threading


def get_page(url):  # 获取URL
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36'}
        r = requests.get(url, headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return '出现异常'  # 异常处理，防止出现错误


def parse_page(html, weather_list):
    soup = BeautifulSoup(html, 'html.parser')
    day_list = soup.find('ul', 't clearfix').find_all('li')
    for day in day_list:
        date = day.find('h1').get_text()
        wea = day.find('p', 'wea').get_text()
        if day.find('p', 'tem').find('span'):  # 判断标签'p','tem'下是否有标签'span'，以此判断是否有最高温
            tem_h = day.find('p', 'tem').find('span').get_text()
        else:
            tem_h = ''  # 最高温
        tem_l = day.find('p', 'tem').find('i').get_text()  # 最低温
        win1 = re.findall('(?<= title=").*?(?=")', str(day.find('p', 'win').find('em')))
        win2 = '-'.join(win1)  # 风向，win1-win2
        level = day.find('p', 'win').find('i').get_text()  # 风力
        weather_list.append([date, wea, tem_l, tem_h, win2, level])




wxPusherUrl = "http://wxpusher.zjiecode.com/api/send/message"

def print_wea(weather_list):
    s = ' \t' * 3
    print(s.join(('日期', '天气', '最低温', '最高温', '风向', '风力')))

    for i in weather_list:
        print(i[0], i[1], i[2], i[3], i[4], i[5])  # 按格式输出
        # 微信推送
        msg = ""
        msg = "江西省南昌市"+i[0]+i[1]+i[2]+i[3]+i[4]+i[5]


def main():
    url = 'http://www.weather.com.cn/weather/101240101.shtml'
    html = get_page(url)
    wea_list = []
    parse_page(html, wea_list)
    print("\t\t\t\t\t\t\t\t\t南昌市近7天天气预报")
    print_wea(wea_list)

    data = {"appToken": "AT_07HilS7jZBSStaq3Xe3KVP50lcSJ1FUU", "content":"江西省南昌市"+"\n"+wea_list[0][0]+"\n"+wea_list[0][1]+"\n"+wea_list[0][2], "summary": "江西省南昌市"+"\n"+wea_list[0][0]+"\n"+wea_list[0][1]+"\n"+wea_list[0][2], "contentType": "1",
            "uids": ["UID_JsYrowR9qlLhefyIHiXSTDatLQYb"]}
    res = requests.post(url=wxPusherUrl, data=json.dumps(data), headers={'Content-Type': 'application/json'})
    print(res.text)


if __name__ == '__main__':
    main()
